package com.airline.dao;

import com.airline.entity.User;
import com.airline.util.DBUtil;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDAO {
    /**
     * 用户登录：根据用户名和密码查询用户
     */
    public User login(String username, String password) {
        User user = null;
        String sql = "SELECT id, username, real_name FROM `user` WHERE username = ? AND password = ?";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            ResultSet rs = pstmt.executeQuery();
            if (rs.next()) {
                user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setRealName(rs.getString("real_name"));
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }

    /**
     * 用户注册：新增用户到数据库
     */
    public boolean register(String username, String password, String realName) {
        String sql = "INSERT INTO `user` (username, password, real_name) VALUES (?, ?, ?)";
        try (Connection conn = DBUtil.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setString(1, username);
            pstmt.setString(2, password);
            pstmt.setString(3, realName);
            return pstmt.executeUpdate() > 0; // 插入成功返回true
        } catch (SQLException e) {
            e.printStackTrace();
            return false; // 用户名重复等异常返回false
        }
    }
}